/*
 * @Date: 2023-12-26 11:29:46
 * @LastEditors: lyx
 * @LastEditTime: 2024-03-07 15:28:34
 * @FilePath: \taro-template3\src\sub_common\pages\auth\wechat-mini-program\index.tsx
 * @Description: 小程序登录页
 */
import { getPhoneNumber } from "@/lib/auth/wechat-mini-program-utils";
import { getSearchParams } from "@/lib/get-search-params";
import { Button, Form, Input, SafeArea } from "@nutui/nutui-react-taro";
import { View, Text } from "@tarojs/components";
import Taro, { navigateTo, switchTab, navigateBack } from "@tarojs/taro";
import { Image } from "@nutui/nutui-react-taro";
import styles from "./index.module.scss";
import { useState } from "react";
import { fetchLogin, fetchUserInfo } from "@/pages/index/services";
import { store } from "@/store/index";
import { setUserInfo } from "@/store/reducers/user";

function WechatMiniProgram() {
  const [loading, setLoading] = useState(false);

  const [username, setUsername] = useState<string>("");
  const [password, setPassword] = useState<string>("");
  const [form] = Form.useForm();


  /**
   * 授权手机号
   */
  const onGetPhoneNumber = (e) => {
    console.log("小程序手机号授权", e);
    if (e.detail.errMsg === "getPhoneNumber:ok") {
      getPhoneNumber(e, () => {
        console.log("getPhoneNumber e", e);
        const backurl = decodeURIComponent(
          decodeURIComponent(getSearchParams("backurl"))
        );
        const isSwitchTab = getSearchParams("isSwitchTab");
        console.log("backurl e", backurl);
        console.log("isSwitchTab e", isSwitchTab);
        if (backurl) {
          const _history = isSwitchTab ? switchTab : navigateTo;
          _history({
            url: backurl,
          });
        } else {
          navigateBack();
        }
      });
    } else if (e.detail.errMsg === "getPhoneNumber:fail no permission") {
      Taro.showToast({
        title: "您的微信小程序无获取用户手机号权限",
        icon: "none",
        duration: 2000,
      });
    } else {
      Taro.showToast({
        title: "您未授权",
        icon: "none",
        duration: 2000,
      });
    }
  };

  const cancelLogin = () => {
    const backurl = decodeURIComponent(
      decodeURIComponent(getSearchParams("backurl"))
    );
    const isSwitchTab = getSearchParams("isSwitchTab");
    console.log("backurl e", backurl);
    console.log("isSwitchTab e", isSwitchTab);
    if (backurl) {
      const _history = isSwitchTab ? switchTab : navigateTo;
      _history({
        url: backurl,
      });
    } else {
      navigateBack();
    }
  };

  const handleSubmit = async () => {
    console.log('username', username);
    console.log('password', password);
    // await form.submit();
  }
  const toLogin = async () => {
    let value: any = form.getFieldsValue(true);
    console.log('toLogin value', value);
    setLoading(true);
    const res = await fetchLogin(value);
    setLoading(false);
    const { isSuccess, msg, content } = res;
    if (isSuccess) {
      Taro.setStorageSync("token", content.token);
      Taro.setStorageSync("refreshToken", content.refreshToken);
      Taro.setStorageSync("tokenHead", content.tokenHead);
      Taro.setStorageSync("tokenHeader", content.tokenHeader);
      Taro.setStorageSync("orgCode", content.orgCode);

      const infoRes = await fetchUserInfo();
      if (infoRes.isSuccess && infoRes.content) {
        store.dispatch(setUserInfo(infoRes.content));

        navigateBack({});
      }
    } else {
      Taro.showToast({
        title: msg,
        icon: "none",
        duration: 2000,
      });
    }

  }

  return (
    <View className={styles["mini-program-login-wrapper"]}>
      <SafeArea position="top"></SafeArea>
      <View className={styles["logo-area"]}>
        {/* <Image
          src={require("@/assets/img/logo/icon-192x192.png")}
          className="w-[100rpx] h-[100rpx]"
        /> */}
        <Text className={styles["text-logo"]}>
          <Text className={styles["text"]}>5T</Text>
        </Text>
        <View className={styles["label-content"]}>
          <Text className={styles["top"]}>
            <Text className={styles["left"]}>产品</Text>
            <Text className={styles["right"]}>研发</Text>
          </Text>
          <Text className={styles["bottom"]}>中控技术</Text>
        </View>
      </View>
      <Form
        form={form}
        divider
        labelPosition="left"
        onFinish={() => {
          toLogin()
        }}
        footer={
          <>
            <Button
              size="large"
              formType="submit"
              block
              type="primary"
              loading={loading}
              disabled={loading}
              onClick={handleSubmit}
            >
              提交
            </Button>
          </>
        }
      >
        <Form.Item required name="username" label="用户名" rules={[
          { required: true, message: '请输入用户名' },
        ]}>
          <Input
            className="nut-input-text"
            placeholder="请输入用户名"
            type="text"
            onChange={setUsername}
          />
        </Form.Item>
        <Form.Item required name="password" label="密码" rules={[
          { required: true, message: '请输入密码' },
        ]}>
          <Input
            className="nut-input-text"
            placeholder="请输入密码"
            type="password"
            onChange={setPassword}
          />
        </Form.Item>
      </Form>
      <View className={styles["btn-content"]}>
        {/* <View className={styles["btn-wx"]}>
          <Button
            block
            type="success"
            size="large"
            open-type="getPhoneNumber"
            onGetPhoneNumber={onGetPhoneNumber}
          >
            微信用户一键登录
          </Button>
        </View> */}
        <View className={styles["btn-wx"]}>
          <Button block size="large" onClick={() => cancelLogin()}>
            返回
          </Button>
        </View>
      </View>
    </View>
  );
}

export default WechatMiniProgram;
